package app.view.component
{
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	import mx.controls.ComboBox;
	import mx.events.CollectionEvent;
	import mx.events.CollectionEventKind;
	import mx.events.FlexEvent;

	public class PackageComboBox extends ComboBox
	{
		private static var sharedData:ArrayCollection;
		
		public function PackageComboBox()		{
			this.editable = true;			
			this.addEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete);
		}
		
		override protected function textInput_changeHandler(event:Event):void{
			super.textInput_changeHandler(event);
			if(collection.filterFunction == null)
	       		collection.filterFunction = filterList;
	       	collection.refresh();
			if(dataCollection.length > 0){
	        	open();
	        }else{
	        	close();
	        }
	    }
	    
	    public function set sharedDataProvider( a:Array):void{
	    	sharedData = new ArrayCollection( a );
	    	dataProvider = sharedData;
	    }
	    
	    override protected function collectionChangeHandler(event:Event):void{
	    	var cevent:CollectionEvent
	    	if (event is CollectionEvent && 
	    		CollectionEvent(event).kind == CollectionEventKind.REFRESH){
	    		invalidateDisplayList();
				return;
	    	}
	    	super.collectionChangeHandler(event);
	    }
	    
		override protected function downArrowButton_buttonDownHandler(event:FlexEvent):void{
	    	collection.filterFunction = null;
	       	collection.refresh();
	       	super.downArrowButton_buttonDownHandler(event);	       
	    }
		
		private function onCreationComplete(event:FlexEvent):void{
			this.removeEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete);
			
			textInput.addEventListener(FlexEvent.ENTER, onTextEnter);
			if(!sharedData)	sharedData = new ArrayCollection();
			dataProvider = sharedData;
		}
		
		private function onTextEnter(event:FlexEvent):void{
			addTextToList();
		}
		
		public function addTextToList():void{
			if(text && isUnique(text))dataCollection.addItem(text);
		}
		
		private function isUnique(txt:String):Boolean{
			 var n:int = 0;
			 while(n<dataCollection.length){
			 	if(txt == dataCollection.getItemAt(n).toString())
			 		return false;
			 	n++;
			 }
			 return true;
		}
	    
	    private function filterList(item:String):Boolean{
	    	var test:String = item.slice(0,text.length);
	    	return (test == text);
	    }
	    
	    private function get dataCollection():ArrayCollection{
	    	return collection as ArrayCollection;
	    }
		
	}
}